
/**
 * 日历选择组件
 * 2018-03-04
 * mehaotian
 * github ：https://github.com/mehaotian
 */
import utils from '../../utils/util.js'
Component({
  /**
   * 组件的属性列表
   * data [Date] 当前现实的月份
   * selected [Date] 默认选择的时间
   */
  properties: {
    date: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        if (newVal){
          this.setData({
            selected: new Date(newVal)
          })
        }
        this.getWeek()
      }
    },
    
    optionalTime:{
      type:Array,
    },
    isOpen: {
      type: Boolean,
      value: false,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    calShow: true, // 日历组件是否打开
    dateShow: false, // 日期是否选择
    selectDay: '', // 当前选择日期
    canlender: {
      'weeks': []
    },
    touchParams: {
      startX: 0,
      startY: 0,
      endX: 0,
      endY: 0
    },
    startTime:null,
    endTime:null,
    pageMothTime:null,
    selected:null,
  },
  ready() {
    this.initStartEndTime()
    this.getWeek()
    if (this.data.isOpen) {
      this.setData({
        calShow: false,
        dateShow: true
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      this.dateSelection()
    },
    initStartEndTime() {
      this.data.pageMothTime = new Date()
      if (this.data.optionalTime.length > 0) {
        this.data.startTime = new Date(this.data.optionalTime[0].replace(/\-/g, "\/"))
        this.data.pageMothTime = this.data.startTime
      }
      if (this.data.optionalTime.length > 1) {
        this.data.endTime = new Date(this.data.optionalTime[1].replace(/\-/g, "\/"))
      }

    },
    getTouchDirection(endX, endY, startX, startY) {
      let space = 50 // 默认大于50算滑动
      let turn = '';
      if (endX - startX > space && Math.abs(endY - startY) < space) { // 右滑
        turn = 'right'
      } else if (endX - startX < -space && Math.abs(endY - startY) < space) { // 左滑
        turn = 'left'
      }
      return turn;
    },
    touchCalendarStart(ev) {
      // console.log('开始触摸', ev)
      this.data.touchParams.startX = ev.changedTouches[0].clientX
      this.data.touchParams.startY = ev.changedTouches[0].clientY
    },
    touchCalendarEnd(ev) {
      // console.log('结束触摸', ev)
      this.data.touchParams.endX = ev.changedTouches[0].clientX
      this.data.touchParams.endY = ev.changedTouches[0].clientY
      let direction = this.getTouchDirection(this.data.touchParams.endX, this.data.touchParams.endY, this.data.touchParams.startX, this.data.touchParams.startY)
      if (!direction) {
        return
      }
      let params = {
        currentTarget: {
          dataset: {
            type: 'month',
            id: direction === 'left' ? '0' : '1'
          }
        }
      }
      // this.dataBefor(params) // 随着移动方向刷新日历
      console.log('移动方向', direction === 'left' ? '左' : '右')
    },
    dateSelection() {
      if (this.data.isOpen) {
        return
      }
      let self = this;
      if (self.data.calShow) {
        self.setData({
          calShow: false
        }, () => {
          setTimeout(() => {
            self.setData({
              dateShow: true
            }, () => {
              // self.triggerEvent('select', {
              //   ischeck: !self.data.calShow
              // })
            })
          }, 100)
        })
      } else {
        self.setData({
          dateShow: false
        }, () => {
          setTimeout(() => {
            self.setData({
              calShow: true
            }, () => {
              // self.triggerEvent('select', {
              //   ischeck: !self.data.calShow
              // })
            })
          }, 300)
        })
      }

    },
    selectDay(e) {
      let index = e.currentTarget.dataset.index;
      let week = e.currentTarget.dataset.week;
      let ischeck = e.currentTarget.dataset.ischeck;
      let canlender = this.data.canlender;
      if (ischeck) return false;
      let month = canlender.weeks[week][index].month < 10 ? '0' + canlender.weeks[week][index].month : canlender.weeks[week][index].month
      let date = canlender.weeks[week][index].date < 10 ? '0' + canlender.weeks[week][index].date : canlender.weeks[week][index].date
      this.data.selected = new Date(canlender.year, month - 1, date)
      this.getWeek();
    },
    packup() {
      if(this.data.selected){
        this.triggerEvent('select', {
              date:this.data.selected
            })
      }else{
        this.triggerEvent('noSelect', {
        })
      }
      // let self = this;
      // if (this.data.isOpen) {
      //   let year = self.data.canlender.year + '-' + self.data.canlender.month + '-' + self.data.canlender.date
      //   let _date = self.getDate(year, 0);
      //   this.data.pageMothTime = _date
      //   self.getWeek();
      //   return
      // }
      // self.setData({
      //   dateShow: false
      // }, () => {
      //   setTimeout(() => {
      //     self.setData({
      //       calShow: true
      //     }, () => {
      //       let year = self.data.canlender.year + '-' + self.data.canlender.month + '-' + self.data.canlender.date
      //       this.data.pageMothTime = self.getDate(year, 0);
      //       self.getWeek();
      //       self.triggerEvent('select', {
      //         ischeck: !self.data.calShow
      //       })
      //     })
      //   }, 300)
      // })
    },
    // 返回今天
    backtoday() {
      this.data.pageMothTime = new Date()
      this.getWeek();
    },
    // 前一天|| 后一天
    dataBefor(e) {
      let num = 0;
      let types = e.currentTarget.dataset.type;

      if (e.currentTarget.dataset.id === '0') {
        num = -1;
      } else {
        num = 1
      }
      let year = this.data.canlender.year + '-' + this.data.canlender.month + '-' + this.data.canlender.date
      this.data.pageMothTime = this.getDate(year, num, types === 'month' ? 'month' : 'day');
      
      this.getWeek();
    },
    // 获取日历内容
    getWeek() {
      let _date = this.data.selected
      console.log('dateData-->', _date)
      // if (typeof dateData !== 'object') {
      //   dateData = dateData.replace(/-/g, '/')
      // }
      // let _date = new Date(dateData);
      let a = this.data.pageMothTime
      let year
      let month
      let date
      let day
      year = a.getFullYear(); //年
      month = a.getMonth() + 1; //月
      date = a.getDate(); //日
      day = a.getDay(); // 天

      
      let canlender = [];
      let dates = {
        firstDay: new Date(year, month - 1, 1).getDay(),
        lastMonthDays: [], // 上个月末尾几天
        currentMonthDys: [], // 本月天数
        nextMonthDays: [], // 下个月开始几天
        endDay: new Date(year, month, 0).getDay(),
        weeks: []
      }

      // 循环上个月末尾几天添加到数组
      for (let i = dates.firstDay; i > 0; i--) {
        dates.lastMonthDays.push({
          'date': new Date(year, month, -i).getDate() + '',
          'month': month - 1
        })
      }
      // 循环本月天数添加到数组
      for (let i = 1; i <= new Date(year, month, 0).getDate(); i++) {
        let have = false;
        
        dates.currentMonthDys.push({
          'date': i + '',
          'month': month
        })
      }
      // 循环下个月开始几天 添加到数组
      for (let i = 1; i < 7 - dates.endDay; i++) {
        dates.nextMonthDays.push({
          'date': i + '',
          'month': month + 1
        })
      }

      canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
      // 拼接数组  上个月开始几天 + 本月天数+ 下个月开始几天
      for (let i = 0; i < canlender.length; i++) {
        let date = new Date(year, canlender[i].month -1, parseInt(canlender[i].date))
        canlender[i].has = false
        if (date.getTime() >= this.data.startTime.getTime() && date.getTime() <= this.data.endTime.getTime()){
          canlender[i].has = true
        }
        if (_date && utils.formatDate(date) === utils.formatDate(_date)){
          canlender[i].isSelect = true
        }
        if (i % 7 == 0) {
          dates.weeks[parseInt(i / 7)] = new Array(7);
        }
        dates.weeks[parseInt(i / 7)][i % 7] = canlender[i]
      }


      // 渲染数据
      this.setData({
        selectDay: month + '月' + date + '日',
        'canlender.weeks': dates.weeks,
        'canlender.month': month,
        'canlender.date': date,
        'canlender.day': day,
        'canlender.year': year,
      })
      console.log('-->',this.data.canlender)
      month = month < 10 ? '0' + month : month
      date = date < 10 ? '0' + date : date
      this.triggerEvent('getdate', {
        year,
        month,
        date
      })
    },
    /**
     * 时间计算
     */
    getDate(date, AddDayCount, str = 'day') {
      if (typeof date !== 'object') {
        date = date.replace(/-/g, '/')
      }
      let dd = new Date(date)
      switch (str) {
        case 'day':
          dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
          break;
        case 'month':
          dd.setMonth(dd.getMonth() + AddDayCount) // 获取AddDayCount天后的日期
          break;
        case 'year':
          dd.setFullYear(dd.getFullYear() + AddDayCount) // 获取AddDayCount天后的日期
          break;
      }
      let y = dd.getFullYear()
      let m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1) // 获取当前月份的日期，不足10补0
      let d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
      return new Date(y,m -1,d)
    }
  },
  attached: function() {
    this.init()
  }
})